package com.cfpamf.ms.insur.wx.request;


import com.cfpamf.ms.insur.wx.model.WxDownloadFundflowModel;
import com.cfpamf.ms.insur.wx.response.WxPayDownloadFundflowResponse;
import com.cfpamf.ms.insur.wx.util.WXPayConstants;
import com.fasterxml.jackson.databind.ObjectMapper;
import jodd.io.ZipUtil;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.zip.ZipException;

/**
 * 下载资金账单
 * <p/>
 * https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_18&index=7
 * <p/>
 * <p>
 * 商户可以通过该接口下载自2017年6月1日起 的历史资金流水账单。
 * 说明：
 * 1、资金账单中的数据反映的是商户微信账户资金变动情况；
 * 2、当日账单在次日上午9点开始生成，建议商户在上午10点以后获取；
 * 3、资金账单中涉及金额的字段单位为“元”。
 */
@Slf4j
public class WxPayDownloadFundflowRequest extends
        WxAbstractRequest<WxDownloadFundflowModel, WxPayDownloadFundflowResponse>
        implements WechatPayDownloadRequest<WxDownloadFundflowModel, WxPayDownloadFundflowResponse> {

    public WxPayDownloadFundflowRequest(WxDownloadFundflowModel model) {
        super(model);
    }

    @Override
    public String getApiAction() {
        return "/pay/downloadfundflow";
    }

    @Override
    public Class<WxDownloadFundflowModel> getObjectClass() {
        return WxDownloadFundflowModel.class;
    }

    @Override
    public Class<WxPayDownloadFundflowResponse> getResponseClass() {
        return WxPayDownloadFundflowResponse.class;
    }

    /**
     * 获取资金流水 需要
     *
     * @return
     */
    @Override
    public boolean requireCert() {
        return true;
    }

    /**
     * 该接口仅仅支持HMACSHA256签名
     *
     * @return
     */
    @Override
    public WXPayConstants.SignType getSignType() {
        return WXPayConstants.SignType.HMACSHA256;
    }

    /**
     * @return
     */
    @Override
    public ResponseHandler<WxPayDownloadFundflowResponse> getResponseHandler(ObjectMapper mapper) {
        return response -> {

            HttpEntity entity = response.getEntity();

            //如果是xml就是访问有问题 如果是gizp说明成功了 应该可以

            Header contentType = entity.getContentType();
            String value = contentType.getValue();
            WxPayDownloadFundflowResponse result = new WxPayDownloadFundflowResponse();
            //如果返回的是gzip 就是正常数据
            if (value.contains("x-gzip")) {
                Path tempDirectory = Files.createTempDirectory("fundFlow");
                Path path = Paths.get(tempDirectory.toString(), "fundFlow" + System.currentTimeMillis() + ".gzip");
                Files.copy(entity.getContent(), path);
//            Files.write(path, entity.getContent());

                try {
//                FileReader fileReader = new FileReader();
                    Path unzipFile = ZipUtil.ungzip(path.toFile()).toPath();
                    @Cleanup BufferedReader reader = Files.newBufferedReader(unzipFile);

                    List<String> allLines = Files.readAllLines(ZipUtil.ungzip(path.toFile()).toPath(), StandardCharsets.UTF_8);
//                result.setDatas(allLines);
                    WxPayDownloadFundflowResponse.parse(allLines, result);
                    result.setReturnCode("SUCCESS");
                    result.setResultCode("SUCCESS");
//
                } catch (ZipException ze) {
                    // 解析失败的时候 嘻嘻嘻
                    log.warn("下载资金账单失败,", ze);
                }
                return result;
            } else {
                //返回的是xml代表下载失败
                String respBody = EntityUtils.toString(entity);
                log.warn("下载资金账单失败==》{}", respBody);
                result = mapper.readValue(respBody, WxPayDownloadFundflowResponse.class);
            }
            return result;
        };
    }
}
